package com.hy.schedule.config;

import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.time.Duration;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:自定义线程池 Bean
 *
 * 自定义线程池可以通过注册自定义的 TaskExecutorBuilder 或者 Executor 来实现，因 TaskExecutorBuilder 不能自定义策略，
 * 这里通过注册自定义 Executor 的扩展类 ThreadPoolTaskExecutor 的方式来实现。
 *
 * 使用自定义线程池Bean，yml文件就不用配置，会发生冲突
 * author: Mr.Du
 * Date: 2023/6/9
 * Time: 13:14
 */
@Configuration
public class TaskExecutorConfig {
    
    //@Lazy
    //@Bean
    //public ThreadPoolTaskExecutor taskExecutor1(TaskExecutionProperties taskExecutionProperties) {
    //    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    //
    //    PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
    //    TaskExecutionProperties.Pool pool = taskExecutionProperties.getPool();
    //    map.from(pool::getQueueCapacity).to(taskExecutor::setQueueCapacity);
    //    map.from(pool::getCoreSize).to(taskExecutor::setCorePoolSize);
    //    map.from(pool::getMaxSize).to(taskExecutor::setMaxPoolSize);
    //    map.from(pool::getKeepAlive).asInt(Duration::getSeconds).to(taskExecutor::setKeepAliveSeconds);
    //    map.from(pool::isAllowCoreThreadTimeout).to(taskExecutor::setAllowCoreThreadTimeOut);
    //    map.from("my-task-").whenHasText().to(taskExecutor::setThreadNamePrefix);
    //
    //    // 默认不设置就是 AbortPolicy
    //    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    //
    //    return taskExecutor;
    //}
    //
    //@Lazy
    //@Bean
    //@Primary
    //public ThreadPoolTaskExecutor taskExecutor2(TaskExecutionProperties taskExecutionProperties) {
    //    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    //
    //    PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
    //    TaskExecutionProperties.Pool pool = taskExecutionProperties.getPool();
    //    map.from(20).to(taskExecutor::setQueueCapacity);
    //    map.from(6).to(taskExecutor::setCorePoolSize);
    //    map.from(10).to(taskExecutor::setMaxPoolSize);
    //    map.from(10).to(taskExecutor::setKeepAliveSeconds);
    //    map.from(true).to(taskExecutor::setAllowCoreThreadTimeOut);
    //    map.from("my-task2-").whenHasText().to(taskExecutor::setThreadNamePrefix);
    //
    //    return taskExecutor;
    //}
}
